<template>

	<view>
		<view class="flex">
			<image @click="onChooseAvatar" class="avatar-wrapper"
				:src="userInfo.UserAvatarURL?userInfo.UserAvatarURL:userAUrl" mode="aspectFit"></image>
			<uni-icons color="#aaa" v-show="showPrivacy" type="eye-filled" size="30" @click="showPrivacy = false">
			</uni-icons>
			<uni-icons color="#aaa" v-show="!showPrivacy" type="eye-slash-filled" size="30" @click="showPrivacy = true">
			</uni-icons>
		</view>
		<uni-list v-if="!realPass" style="margin-top: 10px;">
			<uni-list-item showArrow link
				:to="'/pages/UpdateInfo/updatePage?title=姓名&type=text&value='+userInfo.UserName"
				:rightText="namePass(userInfo.UserName)" title="姓名" />
			<uni-list-item showArrow title="手机号" :rightText="phonePass(userInfo.UserPhone)" />
			<uni-list-item showArrow title="身份证号"
				:to="'/pages/UpdateInfo/updatePage?title=身份证号&type=password&value='+userInfo.IdCard"
				:rightText="idCardPass(userInfo.IdCard)" />
			<!-- <uni-list-item showArrow title="签收授权码" link
				:to="'/pages/UpdateInfo/updatePage?title=签收授权码&type=number&value='+userInfo.smscode"
				:rightText="userInfo.smscode" />
			<uni-list-item showArrow title="认证日期" :rightText="userInfo.createTime" /> -->
			<uni-list-item showArrow title="签名设置" clickable :rightText="setSign" @click="toSignPage" />
		</uni-list>
		<uni-list v-else style="margin-top: 10px;">
			<uni-list-item showArrow :rightText="namePass(userInfo.UserName)" title="姓名" clickable @click="showToast" />
			<uni-list-item showArrow title="手机号" link
				:to="'/pages/UpdateInfo/updatePage?title=手机号&type=number&value='+userInfo.UserPhone"
				:rightText="phonePass(userInfo.UserPhone)" />
			<uni-list-item showArrow title="身份证号" :rightText="idCardPass(userInfo.IdCard)" clickable
				@click="showToast" />
			<!-- <uni-list-item showArrow title="签收授权码" link
				:to="'/pages/UpdateInfo/updatePage?title=签收授权码&type=number&value='+userInfo.smscode"
				:rightText="userInfo.smscode" />
			<uni-list-item showArrow title="认证日期" :rightText="userInfo.createTime" /> -->
			<uni-list-item showArrow title="签名设置" clickable :rightText="setSign" @click="toSignPage" />
		</uni-list>
		<button style="margin-top: 10px;" :disabled="realPass"
			@click="realName">{{realPass?'已 实 名 认 证':'实 名 认 证'}}</button>
		<!-- <button @click="facePass">人脸识别</button>
		<button @click="getLocation">位置</button> -->
	</view>
</template>

<script>
	import {
		idCardPass,
		namePass,
		phonePass
	} from '@/utils/PrivacyPass.js'
	// import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'
	// import {
	// 	type
	// } from 'os';
	export default {
		data() {
			return {
				userInfo: {},
				userAUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
				flag: false,
				token: '',
				remark: {},
				type: 3,
				Vtoken: "",
				realPass: false,
				showPrivacy: true, // 隐私展示
			}
		},
		onShow() {
			let obj = uni.getStorageSync('userInfo')
			this.userInfo = typeof obj == 'object' ? obj : {}
			this.userInfo.UserName = this.userInfo.UserName || ''
			this.userInfo.IdCard = this.userInfo.IdCard || ''
			this.userInfo.UserPhone = this.userInfo.UserPhone || ''
			this.type = uni.getStorageSync('type')
			this.getToken()
			// this.AuthRealName()
			// uni.login({
			// 	provider: 'weixin',
			// 	success: (res) => {
			// 		console.log(res);
			// 	}
			// })
		},
		onLoad() {

			// uni.navigateTo({
			// 	url: '/pages/webView/facePass'
			// })
		},
		computed: {
			setSign() {
				console.log(this.userInfo);
				console.log(typeof this.userInfo.sign);
				return typeof this.userInfo.sign == 'string' ? '已设置' : '未设置'
			}
		},
		onBackPress(options) {
			uni.reLaunch({
				url: '/pages/index/index?Id=' + uni.getStorageSync('Id')
			});
			return true
		},
		methods: {
			async getVToken() {
				await uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/tokenVK?ak=' +
						this.token,
					method: 'GET',
					// header: {
					// 	'Content-Type': 'application/json'
					// },

				}).then(result => {
					let [err, res] = result;
					if (res.data.code == 200) {
						this.Vtoken = JSON.parse(res.data.data).result.verify_token
					}
				})
			},
			getCoordinates(x, y) {
				//GPS坐标

				var ggPoint = new BMapGL.Point(x, y);


				//地图初始化
				// var bm = new BMapGL.Map("allmap");
				// bm.centerAndZoom(ggPoint, 15);
				// bm.addControl(new BMapGL.ZoomControl());

				//添加gps marker和label
				var markergg = new BMapGL.Marker(ggPoint);
				// bm.addOverlay(markergg); //添加GPS marker
				var labelgg = new BMapGL.Label("未转换的GPS坐标（错误）", {
					offset: new BMapGL.Size(10, -10)
				});
				markergg.setLabel(labelgg); //添加GPS label

				//坐标转换完之后的回调函数
				translateCallback = function(data) {
					console.log(data, '------');
					if (data.status === 0) {
						var marker = new BMapGL.Marker(data.points[0]);
						bm.addOverlay(marker);
						var label = new BMapGL.Label("转换后的百度坐标（正确）", {
							offset: new BMapGL.Size(10, -10)
						});
						marker.setLabel(label); //添加百度label
						bm.setCenter(data.points[0]);
					}
				}

				setTimeout(function() {
					var convertor = new BMapGL.Convertor();
					var pointArr = [];
					pointArr.push(ggPoint);
					convertor.translate(pointArr, COORDINATES_WGS84, COORDINATES_BD09, translateCallback)
				}, 1000);


				//      * 坐标常量说明：
				//      * COORDINATES_WGS84 = 1, WGS84坐标
				//      * COORDINATES_WGS84_MC = 2, WGS84的平面墨卡托坐标
				//      * COORDINATES_GCJ02 = 3，GCJ02坐标
				//      * COORDINATES_GCJ02_MC = 4, GCJ02的平面墨卡托坐标
				//      * COORDINATES_BD09 = 5, 百度bd09经纬度坐标
				//      * COORDINATES_BD09_MC = 6，百度b

			},

			getLocation() {
				uni.getLocation({
					type: 'wgs84',
					fail: (err) => {
						console.log(err);
						uni.showToast({
							icon: 'none',
							title: '请打开位置权限'
						})
					},
					success: (res) => {
						console.log(res);
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						var myGeo = new BMapGL.Geocoder();
						// 根据坐标得到地址描述    
						myGeo.getLocation(new BMapGL.Point(res.latitude, res.longitude), function(result) {
							console.log(result)
							if (result) {
								alert(result.address);
							}
						});
						// var map = new BMapGL.Map("container");
						// map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 11);
						// // 创建地理编码实例      
						// var myGeo = new BMapGL.Geocoder();
						// // 根据坐标得到地址描述    
						// myGeo.getLocation(new BMapGL.Point(116.364, 39.993), function(result) {
						// 	if (result) {
						// 		alert(result.address);
						// 	}
						// });


						// this.getCoordinates(res.longitude, res.latitude)
						// var ggPoint = new BMapGL.Point(res.longitude, res.latitude);
						// console.log(ggPoint);
						// var map = new BMapGL.Map("container");
						// map.centerAndZoom(new BMapGL.Point(ggPoint), 11);
						// // // 创建地理编码实例      
						// var myGeo = new BMapGL.Geocoder();
						// console.log(myGeo);
						// let url =
						// 	`/apimap/reverse_geocoding/v3/?ak=${this.token}&output=json&coordtype=wgs84ll&location=${res.latitude},${res.longitude}`
						// uni.request({
						// 	url: url,
						// 	method: 'GET',
						// 	data: {}
						// }).then(data => {
						// 	console.log(data);
						// })

					}
				});
			},
			toSignPage() {
				uni.navigateTo({
					url: '/pages/SignPage/SignPage'
				})
			},
			// 提示
			showToast() {
				// let title = ''
				// if (this.realPass) title = '您已完成实名认证'
				// else title = '您的验证方式为人脸识别,无需进行输入'
				// uni.showToast({
				// 	icon: 'none',
				// 	title
				// })
			},
			// 隐私加密
			idCardPass(text) {
				console.log(text);
				if (this.showPrivacy) return idCardPass(text)
				else return text || ''
			},
			namePass(text) {
				if (this.showPrivacy) return namePass(text)
				else return text || ''
			},
			phonePass(text) {
				if (this.showPrivacy) return phonePass(text)
				else return text || ''
			},
			// 用户头像
			onChooseAvatar(e) {
				if (!this.realPass) return uni.showToast({
					icon: 'none',
					title: '请完成信息验证后再进行头像上传'
				})
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success: (rst) => {
						uni.navigateTo({
							url: '/pages/UpdateInfo/camera?path=' + encodeURIComponent(rst
								.tempFilePaths[0])
						})
					}
				});
			},
			async getverification() {
				uni.showLoading({
					title: '校验签收中,请稍等'
				})
				let flag = false
				await this.$http('post', '/BO/BillList/CheckInfo', {
					"id": uni.getStorageSync('Id') || '',
					"Phone": this.userInfo.UserPhone,
					"Name": this.userInfo.UserName,
					"Card": this.userInfo.IdCard
				}).then(res => {
					if (res.Success) {
						flag = true
						uni.hideLoading()
						uni.showToast({
							title: '校验成功',
							icon: 'none'
						})
					} else {
						flag = false
						uni.showToast({
							title: res.Msg,
							icon: 'none'
						})
					}
				})
				return flag
			},
			async realName() {
				console.log('1');
				// if (this.type == 1) {
				// 	this.facePass()
				// 	return
				// } else {
				// 信息不完善
				if (!this.userInfo.UserName || !this.userInfo.IdCard) {
					return uni.showToast({
						title: '请完善信息',
						icon: 'none'
					})
				}
				let flag = await this.getverification()
				if (!flag) {
					return
				}
				// 非扫码进入
				// if (!uni.getStorageSync('scanCode')) return uni.showToast({
				// 	title: '请扫描二维码,获取公司验证方式',
				// 	icon: 'none'
				// })
				// 百度验证已通过 直接调用保存
				// if (this.flag) this.certification()
				console.log(this.type);
				// this.baiduPass()
				// return
				if (this.type == 0) {
					this.baiduPass()
				} else if (this.type == 2) {
					console.log('1');
					this.threeEle()
				} else {
					this.baiduPass()
				}

				// }
			},
			// 人脸识别
			facePass() {
				uni.showLoading()
				uni.request({
					url: '/api/generate?access_token=' +
						this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: {
						plan_id: '16384'
					}
				}).then(result => {
					uni.hideLoading()
					let [err, res] = result;
					if (err !== null) flag = true
					console.log(res);
					if (res.statusCode == 200) {
						let token = res.data.result.verify_token
						let successUrl = encodeURIComponent(
							'https://bill.yoojet.com/#/pass/facePassLoading')
						let errUrl = encodeURIComponent('https://bill.yoojet.com/#/pass/facePassError')

						let url =
							`token=${token}&successUrl=${successUrl}&failedUrl=${errUrl}`
						let newUrl = encodeURIComponent(url)
						uni.navigateTo({
							url: '/pages/webView/facePass?vt=' +
								token
						})
						// uni.navigateTo({
						// 	url: '/pages/webView/facePass?url=' + newUrl + '&at=' + this.token + '&vt=' +
						// 		token
						// })
					}
				})
			},
			// 三要素
			threeEle() {
				uni.showLoading({
					title: '校验中,请稍等'
				})
				uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/auth3',
					method: 'POST',
					data: {
						"phone": this.userInfo.UserPhone,
						"name": this.userInfo.UserName,
						"idNumber": this.userInfo.IdCard,
						"state": true
					}
				}).then(result => {
					uni.hideLoading()
					let [err, res] = result;
					if (err !== null) flag = true
					if (res.data.code == 200) {
						if (res.data.data) {
							let resp = JSON.parse(res.data.data)
							if (resp.code == 0) {
								this.remark = resp
								this.flag = true
								this.certification()
							} else {
								uni.showToast({
									title: '验证失败,请检查身份信息是否正确',
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: '验证失败,请检查身份信息是否正确',
								icon: 'none'
							})
						}

					} else {
						uni.showToast({
							title: '验证失败,请尝试重新提交',
							icon: 'none'
						})
					}
				})
			},
			async baiduSub() {
				uni.showLoading({
					title: '验证身份中'
				})
				await this.$http('post', '/BO/BillList/IdentityVerification', {
					"id_no": this.userInfo.IdCard,
					"id_name": this.userInfo.UserName,
					"certificate_type": 0,
					"verify_token": this.Vtoken,

				}).then(res => {
					if (res.Success) {
						if (res.Data.success) {
							let successUrl = encodeURIComponent(
								// `https: //hzq.yoojet.com/#/pass/facePassLoading`
								`https://mashangqian.yoojet.com/#/pages/signFor/signFor?Id=${uni.getStorageSync('Id')}&isType=true&Phone=${this.userInfo.UserPhone}`
							)
							let errorUrl = encodeURIComponent(
								`https://mashangqian.yoojet.com/#/?Id=${uni.getStorageSync('Id')}`
							)

							let src =
								`https://h5-faceverify.baidu.com/face/print/?token=${this.Vtoken}&successUrl=${successUrl}&failedUrl=${errorUrl}`
							window.open(src, '_self', '', true)
						} else {
							uni.showToast({
								title: '校验失败',
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: '校验失败',
							icon: 'none'
						})
					}

				})
			},
			// 百度校验身份信息
			baiduPass() {
				uni.showLoading({
					title: '校验中,请稍等'
				})
				uni.request({
					url: 'https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch?access_token=' + this
						.token,
					method: 'POST',
					data: {
						"id_card_number": this.userInfo.IdCard,
						"name": this.userInfo.UserName
					},
					header: {
						'Content-Type': 'application/json' //配置请求头
					},
				}).then(res => {
					uni.hideLoading()

					if (res.length >= 2) {
						let result = res[1]
						if (result.data.error_code == 0) {
							this.flag = true
							this.certification()
						} else {
							uni.showToast({
								title: '校验失败,身份证号与姓名不匹配',
								icon: 'none'
							})
							return
						}
					} else {
						uni.showToast({
							title: '校验失败,身份证号与姓名不匹配',
							icon: 'none'
						})
					}
				})
			},
			// 保存认证记录
			certification() {
				uni.showLoading({
					title: '验证成功保存中'
				})
				uni.request({
					url: this.$veriUrl + '/auth/VeriRecord',
					method: 'POST',
					data: {
						"phone": this.userInfo.UserPhone,
						"name": this.userInfo.UserName,
						"idNumber": this.userInfo.IdCard,
						"state": true,
						VeriType: this.type,
						remark: JSON.stringify(this.remark)
					}
				}).then(async result => {
					let [err, res] = result;
					if (err !== null) flag = true
					if (res.data.code == 200) {
						uni.hideLoading()
						uni.showToast({
							title: '验证成功',
							icon: 'none'
						})
						uni.setStorageSync('userInfo', this.userInfo);
						setTimeout(async () => {
							if (this.type == 1) {
								await this.getVToken()
								await this.baiduSub()
								// let successUrl = encodeURIComponent(
								// 	// `https: //hzq.yoojet.com/#/pass/facePassLoading`
								// 	`https://mashangqian.yoojet.com/#/pages/signFor/signFor?Id=${uni.getStorageSync('Id')}&isType=true`
								// )
								// let errorUrl = encodeURIComponent(
								// 	`https://mashangqian.yoojet.com/#/?Id=${uni.getStorageSync('Id')}`
								// )

								// let src =
								// 	`https://h5-faceverify.baidu.com/face/print/?token=${this.Vtoken}&successUrl=${successUrl}&failedUrl=${errorUrl}`
								// window.open(src, '_self', '', true)
								return
							}
							uni.reLaunch({
								url: `/pages/signFor/signFor?Id=${uni.getStorageSync('Id')}&isType=true`
							})
						}, 500)
					} else {
						uni.showToast({
							title: '验证失败,请尝试重新提交',
							icon: 'none'
						})
					}
				})
			},
			// 获取TOKEN
			async getToken() {
				await uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/token?phone=' + this.userInfo.UserPhone,
					method: 'GET'
				}).then(result => {
					let [err, res] = result;
					if (res.data.code == 200) {
						this.token = JSON.parse(res.data.data).access_token
						console.log(this.token);
					}
				})
			},
			// 验证是否实名认证
			async AuthRealName() {
				await uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/state?Value=' + this.userInfo.UserPhone,
					method: 'GET'
				}).then(result => {
					let [err, res] = result;
					if (res.data.code == 200) {
						this.realPass = true,
							this.userInfo = {
								...res.data.data,
								...this.userInfo
							}
						// this.userInfo = {
						// 	...res.data.data,
						// 	name: res.data.data.name || this.userInfo.UserName,
						// 	phone: res.data.data.phone || this.userInfo.UserPhone,
						// 	idCard: res.data.data.idNumber || this.userInfo.IdCard,
						// 	avatarUrl: res.data.data.avatarUrl || this.userInfo.UserAvatarURL,
						// 	smscode: res.data.data.smscode || this.userInfo.smscode,
						// }
						if (this.userInfo.UserName) this.getBG(this.userInfo.UserName)
						else uni.removeStorageSync('nameBG')
					} else {
						this.realPass = false
					}
					uni.setStorageSync('userInfo', this.userInfo)
				})
			},
			getBG(name) {
				this.$http('post', '/Base_Manage/Upload/GetNameSign?Name=' + name).then(res => {
					if (res.Success) uni.setStorageSync('nameBG', res.Data)
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.avatar-wrapper {
		margin: 10px 0 0 10px;
		border: none;
		background-color: transparent;
		width: 100px;
		height: 100px;
		padding: 0;
		border-radius: 5px;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.flex {
		display: flex;
		justify-content: space-between;
		align-items: baseline;
	}
</style>